package cn.com.ddapp.ddm.ui.mine;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.mine.PayInfoEntity;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.pay.PayCallback;
import cn.com.ddapp.ddm.pay.alipay.AlipayProvider;
import cn.com.ddapp.ddm.pay.alipay.PayObject;
import cn.com.ddapp.ddm.pay.wx.WXProvider;
import cn.com.ddapp.ddm.pay.wx.WXProviderScan;
import cn.com.ddapp.ddm.polling.MinePollingService;
import cn.com.ddapp.ddm.polling.PollingService;
import cn.com.ddapp.ddm.polling.PollingUtils;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.QRUtil;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import okhttp3.Call;

public class PayMoneyActivity extends BaseActivity{

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titletext)
    TextView titletext;
    @BindView(R.id.pay_amount)
    TextView payAmount;
    @BindView(R.id.wechat)
    ImageView wechat;
    @BindView(R.id.pay1)
    TextView pay1;
    @BindView(R.id.checkboxWechat)
    ImageView checkboxWechat;
    @BindView(R.id.logo2)
    ImageView logo2;
    @BindView(R.id.pay2)
    TextView pay2;
    @BindView(R.id.checkboxAlipay)
    ImageView checkboxAlipay;
    @BindView(R.id.pay)
    TextView pay;
    @BindView(R.id.error_layout)
    EmptyLayout errorLayout;

    private double money;
    //private int money;
    Dialog dialog;
    String userId;
    String rechargeNo;
    private int payType = 1;//1微信支付 2 支付宝支付
    private boolean isRegister = false;

    @Override
    public void initView() {
        titletext.setText("选择充值方式");
        back.setOnClickListener(this);
        userId = SPUtils.getStringData(PayMoneyActivity.this, SPUtils.USERID);
        money = Double.parseDouble(getIntent().getStringExtra("money"));
        Log.e("111","money="+getIntent().getStringExtra("money"));
        //money = Integer.parseInt(getIntent().getStringExtra("money").trim());
        //money = new BigInteger(getIntent().getStringExtra("money").trim());
        payAmount.setText("￥"+NetUtils.setDecimal(money));
        checkboxWechat.setOnClickListener(this);
        pay.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_pay_money;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }

    private void  clearImgs(){
        checkboxWechat.setImageResource(R.drawable.circle_unchecked);
        checkboxAlipay.setImageResource(R.drawable.circle_unchecked);
    }

    @OnClick({R.id.back,R.id.pay,R.id.checkboxWechat,R.id.checkboxAlipay})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.back :
                finish();
                break;
            case R.id.pay :
                if (!NetUtils.isConnected(this)) {
                    Toast.makeText(this, "请检查你的网络", Toast.LENGTH_SHORT).show();
                } else {
                    OkUtilCallback callback = new OkUtilCallback() {
                        @Override
                        public void onMyResponse(String response, int id) {
                            Gson gson = new Gson();
                            PayInfoEntity entity = gson.fromJson(response, PayInfoEntity.class);
                            if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                                BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                            } else {
                                if (entity.getRechargeNo()!=null){
                                    rechargeNo = entity.getRechargeNo();
                                    Log.e("111","rechargeNo="+rechargeNo);
                                    payAction(rechargeNo);
                                }
                            }
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            super.onError(call, e, id);
                            BaseApplication.showToast(e.toString());
                        }
                    };
                    /*amount double[Y] 金额
                    payType int[y]支付方式 微信1，支付宝2
                    userId int[Y] 用户ID*/
                    OKUtilAPI.post(OKUtilAPI.userRecharge, "amount=" + money + "&payType=" + payType + "&userId=" + userId, callback);
                }

                break;
            //微信支付
            case R.id.checkboxWechat :
                clearImgs();
                checkboxWechat.setImageResource(R.mipmap.right);
                payType = 1;
                break;
            //支付宝支付
            case R.id.checkboxAlipay :
                clearImgs();
                checkboxAlipay.setImageResource(R.mipmap.right);
                payType = 2;
                break;
        }
    }

    private void payAction(final String orderNo){
        if(payType==1&&!TDevice.isTablet(getApplicationContext())){
            //非平板微信支付
            PayObject payObject = new PayObject();
            payObject.setBody("微信充值");
            payObject.setName("微信充值");
            payObject.setPrice(money+"");
            payObject.setOrderNo(orderNo);
//            payObject.setOrderId(entity.getOrder().getOrderNo());
            payObject.setNotify_url(OKUtilAPI.WEIXIN_RECHARGEPAY_CALLBACK);//微信充值回调
            WXProvider wxProvider = new WXProvider(PayMoneyActivity.this,payObject);
            wxProvider.pay();
        } else if(payType==1&& TDevice.isTablet(getApplicationContext())){
            //平板微信支付 微信扫码支付
            PayObject payObject = new PayObject();
            payObject.setBody("微信充值");
            payObject.setName("微信充值");
            payObject.setPrice(money+"");
            payObject.setOrderNo(orderNo);
//            payObject.setOrderId(entity.getOrder().getOrderNo());
            payObject.setNotify_url(OKUtilAPI.RECHARGE_SCAN_CALLBACK);
            WXProviderScan wxProvider = new WXProviderScan(PayMoneyActivity.this,payObject);
            wxProvider.setCodeUrlSuccessListener(new WXProviderScan.CodeUrlSuccessListener() {
                @Override
                public void onCodeUrlSuccessListerer(Map<String, String> result) {
                    if("fail".equalsIgnoreCase(result.get("result_code"))){
                        BaseApplication.showToast(result.get("err_code_des"));
                    }else if("success".equalsIgnoreCase(result.get("result_code"))){
                        dialog = new Dialog(PayMoneyActivity.this, R.style.Transparent);
                        dialog.setContentView(R.layout.dialog_pay_qr);
                        dialog.setCanceledOnTouchOutside(true);
                        ImageView bitmap = (ImageView)dialog.findViewById(R.id.qr);
                        bitmap.setImageBitmap(QRUtil.createQRImage(result.get("code_url"),200,200));
                        Window win = dialog.getWindow();
                        win.setGravity( Gravity.CENTER);
//                        win.getDecorView().setPadding(0, 0, 0, 0);
                        WindowManager.LayoutParams lp = win.getAttributes();
                        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                        lp.dimAmount = 0.5f;
                        win.setAttributes(lp);
                        dialog.show();
                        IntentFilter intentFilter = new IntentFilter(MinePollingService.ACTION);
                        isRegister = true;
                        registerReceiver(receiver,intentFilter);
                        PollingUtils.startPollingService(PayMoneyActivity.this, 1, MinePollingService.class, MinePollingService.ACTION,orderNo, PollingService.WECAHT);
                    }
                }
            });
            wxProvider.pay();
        }
        //支付宝支付
        else if (payType == 2){
            //支付宝支付
            PayObject payObject = new PayObject();
            payObject.setBody("支付宝充值");
            payObject.setName("支付宝充值");
            payObject.setPrice(money+"");
            payObject.setOrderNo(orderNo);
            payObject.setNotify_url(OKUtilAPI.ALIPAY_RECHARGEPAY_CALLBACK);
            AlipayProvider alipayProvider = new AlipayProvider(PayMoneyActivity.this,payObject, new PayCallback() {

                @Override
                public void callback(int paycode) {
                    if(paycode==AlipayProvider.PAY_SUCCESS){
                    }
                }
            });
            alipayProvider.pay();;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(isRegister){
            unregisterReceiver(receiver);
            PollingUtils.stopPollingService(this, MinePollingService.class, MinePollingService.ACTION);
        }
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean status = intent.getBooleanExtra("status",false);
            if(status){
                if(isRegister){
                    unregisterReceiver(receiver);
                    isRegister = false;
                    PollingUtils.stopPollingService(PayMoneyActivity.this, MinePollingService.class, MinePollingService.ACTION);
                }
                BaseApplication.showToast(R.string.mine_pay_success);
                if(dialog!=null){
                    dialog.dismiss();
                }
            }
        }
    };
}
